package com.hanxiaozhang.stackandqueue;

/**
 * 〈一句话功能简述〉<br>
 * 〈使用数组创建栈〉
 *
 * @author hanxinghua
 * @create 2021/9/7
 * @since 1.0.0
 */
public class StackArray {

    public static void main(String[] args) {
        StackArray myStackArray = new StackArray(4);
        myStackArray.push(1);
        myStackArray.push(2);
        myStackArray.push(3);
        myStackArray.push(4);
        myStackArray.printStackHeadWhile();
        System.out.println("-------");
        System.out.println(myStackArray.pop());
        System.out.println(myStackArray.pop());
        System.out.println(myStackArray.pop());
        System.out.println(myStackArray.pop());
    }

    /**
     * 数组
     */
    private int[] array;

    /**
     * 索引
     */
    private int index;


    /**
     * 大小
     */
    private int size;

    /**
     * 容量
     */
    private final int capacity;

    public StackArray(int capacity) {
        array = new int[capacity];
        index = 0;
        size = 0;
        this.capacity = capacity;
    }


    public void push(int value) {
        if (size == capacity) {
            throw new RuntimeException("StackArray is full, not push");
        }
        size++;
        array[index] = value;
        index = ++index;
    }

    public int pop() {
        if (size == 0) {
            throw new RuntimeException("StackArray is null, not pop");
        }
        size--;
        int ans = array[index];
        index = --index;
        return ans;
    }

    public boolean isEmpty() {
        return size == 0;
    }


    /**
     * 栈顶打印原始
     */
    public void printStackHeadWhile() {
        System.out.println("-------");
        int printIndex = --index;
        for (int s = 0; s < size; s++) {
            System.out.println(array[printIndex]);
            printIndex = --printIndex;
        }
    }


}
